package xyz.lspace.newlrshk;

import java.io.*;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class SocketClient {

    private String host;
    private Integer port;

    public SocketClient(String host, Integer port) {
        this.host = host;
        this.port = port;
    }
    //向服务器发送信息
    public String sendMsg(final String msg) {

        FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                try {
                    Socket s = new Socket(host,port);
                    //构建IO
                    InputStream is = s.getInputStream();
                    OutputStream os = s.getOutputStream();
                    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
                    //向服务器端发送一条消息
                    bw.write(msg+"\n");
                    bw.flush();
                    //读取服务器返回的消息
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String mess = br.readLine();
                    return mess;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
        new Thread(futureTask).start();
        try {
            return  futureTask.get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }
}
